<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Layout
 *
 * @author Aluno
 */
class MY_Parser extends CI_Parser {

    private $_css = array();
    private $_js = array();
    private $ci = null;
    private $title = '';
    private $title_pagina = array('link' => null, 'title' => null);
    private $template = '';
    private $meta = array();
    private $config = '';
    private $msg = '';

    //put your code here
    public function __construct() {
        $this->ci = &get_instance();
        $this->ci->load->helper('html');
        $this->config = $this->ci->config->item($this->ci->uri->segment(1));
        $this->config_default = $this->ci->config->item('default');
    }

    public function site_view($view = '', $dados = array(), $retorno = FALSE) {
        $v_dados = array();
        $v_dados['conteudo'] = ($view != '' ? $this->parse($view, $dados, TRUE) : '');
        $v_dados['title'] = $this->title;
        $v_dados['meta'] = meta($this->meta);
        $v_dados['title_pagina'] = anchor($this->title_pagina['link'], $this->title_pagina['title']);
        $v_dados['uri_string'] = $this->ci->uri->uri_string();
        $v_dados['css'] = $this->get_css();
        $v_dados['js'] = $this->get_js();
        $v_dados['msg_sistema'] = $this->get_msg();
        $this->parse(str_replace('/', '_', $this->template), $v_dados, $retorno);
    }

    public function set_title_pagina($title_pagina, $link = '') {
        $this->title_pagina = array('link' => base_url($link), 'title' => $title_pagina);
    }

    public function set_title($title) {
        $this->title = $title;
    }

    public function set_meta($descricao, $tipo = 'description') {
        $count = count($this->meta);
        $this->meta[$count]['name'] = $tipo;
        $this->meta[$count]['content'] = $descricao;
    }

    public function tratar_meta($descricao) {
        $explod = explode(' ', str_replace(array(',', '.', ';', '>', '<', '?', '!', '{', '}', '(', ')', '[', ']', '_', '+', '*', '/', '\\', '|'), ' ', strip_tags($descricao)));
        $retorno = array();
        if (count($explod) > 0) {
            foreach ($explod as $key => $value) {
                $value = trim($value);
                if ($value != '') {
                    $retorno[$value] = $value;
                }
            }
            return implode(', ', $retorno);
        }
        return $retorno;
    }

    public function set_template($template) {
        $this->template = $template;
    }

    public function get_template() {
        return $this->template;
    }

    public function get_css() {
        $css = '';
        if (count($this->_css) > 0) {
            foreach ($this->_css as $v) {
                if (file_exists(FCPATH . $this->config['arquivos_dir'] . $v)) {
                    $css .= '<link rel="stylesheet"  href="' . base_url() . $this->_mindifyte($v, FCPATH . $this->config['arquivos_dir']) . '" />' . "\n";
                } else if (file_exists(FCPATH . $this->config_default['arquivos_dir'] . $v)) {
                    $css .= '<link rel="stylesheet"  href="' . base_url() . $this->_mindifyte($v, FCPATH . $this->config_default['arquivos_dir']) . '" />' . "\n";
                }
            }
        }
        return $css;
    }

    public function set_css($_css) {
        $this->_css[] = $_css;
        $this->_css = array_unique($this->_css);
    }

    public function get_js() {
        $js = '';

        if (count($this->_js) > 0) {
            foreach ($this->_js as $v) {
                if (file_exists(FCPATH . $this->config['arquivos_dir'] . $v)) {
                    $js .= '<script src="' . base_url() . $this->config['arquivos_dir'] . $v . '"></script>' . "\n";
                } else if (file_exists(FCPATH . $this->config_default['arquivos_dir'] . $v)) {
                    $js .= '<script src="' . base_url() . $this->config_default['arquivos_dir'] . $v . '"></script>' . "\n";
                }
            }
        }
        return $js;
    }

    public function set_js($_js) {
        $this->_js[] = $_js;
        $this->_js = array_unique($this->_js);
    }

    private function _mindifyte($v, $diretorio) {
        $CI = &get_instance();
        $CI->load->helper('file');

        $info_a = get_file_info($diretorio . $v);
        $info_server_path = dirname($info_a['server_path']);
        $info_name = basename($info_a['server_path']);
        $info_a = $info_a['date'];
        $info_b = get_file_info($diretorio . 'min' . DIRECTORY_SEPARATOR . $v);
        $info_b = ($info_b != FALSE ? $info_b['date'] : FALSE);

        $mid = TRUE;

        if ($info_b != FALSE) {
            if ($info_a <= $info_b) {
                $mid = FALSE;
            }
        }

        if ($mid == TRUE) {
            $ler = read_file($info_server_path . DIRECTORY_SEPARATOR . $info_name);
            $ler = str_replace('{base_url}', base_url(), $ler);
            $ler = str_replace('{base_adm}', base_adm() . '/', $ler);
            $ler = str_replace('{base_site}', base_site() . '/', $ler);
            $ler = str_replace('{base_img_site}', base_img_site() . '/', $ler);
            $ler = str_replace('{base_img_adm}', base_img_adm() . '/', $ler);
            $ler = str_replace('{base_theme}', (base_url(ltrim($this->config['arquivos_dir'], '/')) . '/'), $ler);
            $ler = str_replace('{base_theme_default}', (base_url(ltrim($this->config_default['arquivos_dir'], '/')) . '/'), $ler);
            $ler = str_replace(array("\n", "\t", "\r"), '', $ler);
            $ler = $this->_optimize($ler);
            if (!file_exists($info_server_path . DIRECTORY_SEPARATOR . 'min')) {
                mkdir($info_server_path . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR, DIR_WRITE_MODE, TRUE);
            } else {
                @chmod($info_server_path . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR, DIR_WRITE_MODE);
            }
            write_file($info_server_path . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR . $info_name, $ler);
        }
        return str_replace(FCPATH, '', $info_server_path) . DIRECTORY_SEPARATOR . 'min' . DIRECTORY_SEPARATOR . $info_name;
    }

    /**
     * Optimize
     * Optimize the contents of a css file
     * based on Drupal 7 CSS Core aggregator
     *
     * @param string $contents
     * @return string
     */
    private function _optimize($contents) {
// Perform some safe CSS optimizations.
// Regexp to match comment blocks.
        $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
// Regexp to match double quoted strings.
        $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
// Regexp to match single quoted strings.
        $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
// Strip all comment blocks, but keep double/single quoted strings.
        $contents = preg_replace("<($double_quot|$single_quot)|$comment>Ss", "$1", $contents);


        return $contents;
    }

    /**
     *  Parse a template
     *
     * Parses pseudo-variables contained in the specified template,
     * replacing them with the data in the second param
     *
     * @access	public
     * @param	string
     * @param	array
     * @param	bool
     * @return	string
     */
    function _parse($template, $v_dados, $return = FALSE) {

        $v_dados['base_url'] = base_url();
        $v_dados['base_adm'] = base_adm() . '/';
        $v_dados['base_site'] = base_site() . '/';
        $v_dados['base_img_site'] = base_img_site() . '/';
        $v_dados['base_img_adm'] = base_img_adm() . '/';
        $v_dados['base_theme'] = base_url(ltrim($this->config['arquivos_dir'], '/')) . '/';


        $template = $this->replace_modules(parent::_parse($template, $v_dados, TRUE));



        if ($return == FALSE) {
            $CI = &get_instance();
            $CI->output->append_output($template);
        }
        return $template;
    }

    private function replace_modules($template) {

        $pattern = '/({include:(.*)})/i';
        $matches = null;
        preg_match_all($pattern, $template, $matches, PREG_SET_ORDER);
        if (count($matches) > 0) {
            foreach ($matches as $v) {
                $ex = explode(':', $v[2]);
                if (strtolower($ex[0]) === 'controller') {
                    $template = str_replace($v[0], $this->ci->load->controller($ex[1], (isset($ex[2]) ? explode('|', $ex[2]) : array())), $template);
                } else if (strtolower($ex[0]) === 'view') {
                    $template = str_replace($v[0], $this->ci->load->view($ex[1], (isset($ex[2]) ? explode('|', $ex[2]) : array()), true), $template);
                }
            }
        }

        return $template;
    }

    public function set_msg($msg, $tipo = 'info') {
        $this->msg = '<h4 id="msg_sistema" class="alert_' . trim($tipo) . '">' . trim($msg) . '</h4>';
    }

    public function get_msg() {
        return ($this->msg == NULL ? '<h4 id="msg_sistema" class=""></h4>' : $this->msg);
    }

}
